package carcassonne.server.http.controller;

import carcassonne.lobby.RoomInfo;
import carcassonne.lobby.RoomManager;
import carcassonne.server.http.HttpContext;
import carcassonne.server.http.HttpParams;
import carcassonne.server.ioc.Controller;
import carcassonne.server.ioc.HttpMessageHandler;
import carcassonne.server.ioc.RequestMapping;
import carcassonne.user.UserInfo;
import carcassonne.user.UserManager;
import com.alibaba.fastjson.JSON;

import java.util.List;

import static carcassonne.server.ioc.HttpMessageDispatcher.Get;
import static carcassonne.server.ioc.HttpMessageDispatcher.Post;

@Controller
@RequestMapping(value = "/lobby")
public class LobbyController {

    @HttpMessageHandler(method = Post, path = "/room")
    public void CreateRoom(HttpContext context, HttpParams params) {
        if (!params.Has("token")) {
            context.ResponseForbidden("need token!");
            return;
        }
        String token = params.GetString("token");

        if (!CheckLogin(context, token)) return;

        // 这个用户首先不能已经在房间
        UserInfo userInfo = UserManager.GetInstance().GetUserInfoWithToken(token);
        if (userInfo == null) {
            context.ResponseForbidden("user not login");
            return;
        }

        RoomInfo roomInfo = params.GetObject("room", RoomInfo.class);
        if (roomInfo == null) {
            context.ResponseForbidden("wrong room info");
            return;
        }
        roomInfo.name = userInfo.nickname + "的房间";

        String roomID = RoomManager.GetInstance().PrepareRoom(roomInfo);
        context.ResponseOK(roomID);
    }

    @HttpMessageHandler(method = Get, path = "/rooms")
    public void GetRoomList(HttpContext context, HttpParams params) {
        List<RoomInfo> roomInfos = RoomManager.GetInstance().GetRoomList();
        context.ResponseOK(JSON.toJSONString(roomInfos.toArray()));
    }

    @HttpMessageHandler(method = Get, path = "/test")
    public void Test(HttpContext context, HttpParams params) {
        context.ResponseOK("token: 123");
    }

    // 判断是不是登录用户
    public boolean CheckLogin(HttpContext context, String token) {
        if (!UserManager.GetInstance().IsLoginUser(token)) {
            context.ResponseForbidden("user not login");
            return false;
        }
        return true;
    }
}
